from django.shortcuts import render
from django.views import View
from django import http
import re
from django.contrib.auth import login, authenticate

from .models import User
from utils.response_code import RETCODE


class RegisterView(View):
    """注册"""

    def get(self, request):
        return render(request, "register.html")

    def post(self, request):
        # 1、接收请求体数据
        query_dict = request.POST
        username = query_dict.get('username')
        password = query_dict.get('password')
        password2 = query_dict.get('password2')
        mobile = query_dict.get('mobile')
        sms_code = query_dict.get('sms_code')
        allow = query_dict.get('allow')
        # 2、校验数据
        if all([username, password, password2, mobile, sms_code, allow]) is False:
            return http.HttpResponseForbidden("缺少必传参数")

        if not re.match(r"^[a-zA-Z0-9_-]{2,20}$", username):
            return http.HttpResponseForbidden("请输入2-20个字符的用户名")

        if not re.match(r"^[0-9A-Za-z]{8,20}$", password):
            return http.HttpResponseForbidden("请输入8-20个字符的密码")
        if password != password2:
            return http.HttpResponseForbidden("两次输入的密码不一致")

        if not re.match(r"^1[3-9]\d{9}$", mobile):
            return http.HttpResponseForbidden("请输入正确的手机号")

        # TODO 验证码功能后续再弄
        # 3、创建user并存储到数据库表中
        user = User.objects.create_user(username=username, password=password, mobile=mobile)
        # request.session['id'] = user.id  # 用户注册成功要保持状态
        # 状态保持
        login(request, user)

        # 4、响应，注册成功即登录成功
        return http.HttpResponse("注册成功啦！！！！")


class UsernameCount(View):
    """判断用户名是否重复"""

    def get(self, request, username):
        # 查询user表，查询username的数量
        count = User.objects.filter(username=username).count()
        # 包装响应数据
        data = {
            'count': count,
            'code': RETCODE.OK,  # 自定义状态码
            'errmsg': 'OK',
        }
        return http.JsonResponse(data)


class MobileCountView(View):
    """判断手机号是否重复"""

    # 查询user表，查询mobile的数量
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        # 包装响应数据
        data = {
            'count': count,
            'code': RETCODE.OK,  # 自定义状态码
            'errmsg': 'OK',
        }
        return http.JsonResponse(data)


class LoginView(View):
    """登录"""

    def get(self, request):
        return render(request, "login.html")

    def post(self, request):
        # 接收请求表单数据
        query_dict = request.POST
        print(query_dict.dict().keys())
        username = query_dict.get('username')
        password = query_dict.get('password')
        remembered = query_dict.get('remembered')

        # 校验
        if all([username, password]) is False:
            return http.HttpResponseForbidden("缺少必传参数")
        # 用户登录验证
        user = authenticate(request, username=username, password=password)
        # 判断用户是否通过是否认证
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})
        # 状态保持
        login(request, user)
        # 如果用户没有勾选记住登录，设置session过期时间为会话结束
        if remembered is None:
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(3600 * 24 * 7)
        # 重定向到首页
        return http.HttpResponse("登录成功，跳转到首页界面")
